package com.jdy.haoduoai.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.BannerAdapter.OnBannerClickListener;
import com.jdy.haoduoai.adapter.CategoryGridViewAdapter.OnGridItemClickListener;
import com.jdy.haoduoai.adapter.RecentPlayAdapter;
import com.jdy.haoduoai.model.LeBanner;
import com.jdy.haoduoai.model.LePlaybackRecordItem;
import com.jdy.haoduoai.model.LePlaybackRecordWrapper;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

//import com.jdy.haoduoai.R;

/**
 * 近期播放记录
 * 
 * @author hf
 * 
 */

public class RecentPlayActivity extends BaseActivity implements
    OnGridItemClickListener, OnBannerClickListener, OnScrollListener,
    OnClickListener, OnRefreshListener,
    StickyListHeadersListView.OnHeaderClickListener,
    StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
    StickyListHeadersListView.OnStickyHeaderChangedListener {

  private static final String TAG = RecentPlayActivity.class.getSimpleName();

  @InjectView(id = R.id.content_views)
  private StickyListHeadersListView listview;

  private boolean fadeHeader = true;

  private RecentPlayAdapter adapter;
  private ArrayList<LePlaybackRecordWrapper> mList;
  private ArrayList<LePlaybackRecordItem> mPlaybackList = null;
  private ArrayList<LePlaybackRecordItem> mPlaybackList2 = null;
  private LeUser mLeUser;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recentplay);
    // hideTitleView();
    setTitle("近期播放记录");
    initialize();

    initData();
  }

  private void initData() {
    Async.start(new Func0<ResponseResult>() {
      @Override
      public ResponseResult call() {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/history", param_, HttpUtils.TAG_GET_REQUEST);
      }
    }).filter(new Func1<ResponseResult, Boolean>() {
      @Override
      public Boolean call(ResponseResult arg0) {
        return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
      }
    }).subscribe(new Action1<ResponseResult>() {
      @SuppressWarnings("unchecked")
      @Override
      public void call(ResponseResult arg0) {
        if (Tools.isNotEmpty(arg0) && Tools.isNotEmpty(arg0.data)) {
          try {
            JSONObject result = new JSONObject(arg0.data);
            Iterator<?> it = result.keys();
            String keyDate = null;
            while (it.hasNext()) {// 遍历JSONObject
              keyDate = it.next().toString();

              if (Tools.isNotEmpty(keyDate)) {
                JSONArray playList = result.getJSONArray(keyDate);// 获取JSONArray
                if (Tools.isNotEmpty(playList)) {
                  ArrayList<LePlaybackRecordItem> list = (ArrayList<LePlaybackRecordItem>) JsonSerializer
                      .getInstance().deserialize(playList.toString(),
                          ArrayList.class, LePlaybackRecordItem.class);
                  if (Tools.isNotEmpty(list)) {
                    LePlaybackRecordWrapper itemVo = new LePlaybackRecordWrapper();
                    itemVo.dateTag = keyDate;// );
                    itemVo.list = list; // );
                    mList.add(itemVo);
                  }
                }
              }
            }

          } catch (JSONException e) {
            e.printStackTrace();
          }

          runOnUiThread(new Runnable() {

            @Override
            public void run() {
              setView();

            }
          });

        }
      }
    });
  }

  private void initialize() {
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    mList = new ArrayList<LePlaybackRecordWrapper>();
    mPlaybackList = new ArrayList<LePlaybackRecordItem>();
    mPlaybackList2 = new ArrayList<LePlaybackRecordItem>();

    // listview.setOnItemClickListener(this);
    listview.setOnHeaderClickListener(this);
    listview.setOnStickyHeaderChangedListener(this);
    listview.setOnStickyHeaderOffsetChangedListener(this);
    // stickyList.addHeaderView(getLayoutInflater().inflate(R.layout.list_header,
    // null));
    // stickyList.addFooterView(getLayoutInflater().inflate(R.layout.list_footer,
    // null));
    // listview.setEmptyView(findViewById(R.id.empty));
    listview.setDrawingListUnderStickyHeader(true);
    listview.setAreHeadersSticky(true);
    // listview.setAdapter(mAdapter);
  }

  private void setView() {
    // // row 1
    // LePlaybackRecordWrapper itemVo = new LePlaybackRecordWrapper();
    // itemVo.setDateTag("2016-04-09 周六");
    //
    // for (int i = 0; i < 8; i++) {
    // LePlaybackRecordItem item = new LePlaybackRecordItem();
    // mPlaybackList.add(item);
    // }
    // itemVo.setList(mPlaybackList);
    // mList.add(itemVo);
    //
    // // row 2
    // itemVo = new LePlaybackRecordWrapper();
    // itemVo.setDateTag("2016-04-08 周五");
    //
    // for (int i = 0; i < 8; i++) {
    // LePlaybackRecordItem item = new LePlaybackRecordItem();
    // mPlaybackList2.add(item);
    // }
    // itemVo.setList(mPlaybackList2);
    // mList.add(itemVo);

    setAdapter();
  }

  @Override
  public void onClick(View v) {

    switch (v.getId()) {
    case R.id.editbox:
      if (LeConfig.isLogin) {
        Intent toSearch = new Intent(this, SearchActivity.class);
        toSearch.putExtra("type", "cartoon");
        startActivity(toSearch);
      } else {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
      }

      break;
    case R.id.device_stateview:
      Intent intent = new Intent();
      if (LeConfig.isLogin) {
        intent.setClass(this, DevicePropertyActivity.class);
      } else {
        intent.setClass(this, LoginActivity.class);
      }

      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      startActivity(intent);

      break;
    case R.id.img_back:
      this.finish();
      break;

    default:
      break;
    }

  }

  @Override
  public void onResume() {
    super.onResume();

    MobclickAgent.onPageStart(TAG);
  }

  @Override
  public void onPause() {
    super.onPause();
    MobclickAgent.onPageEnd(TAG);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

  }

  @Override
  public void onGridItemClik(int pos) {

  }

  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {

  }

  @Override
  public void onScroll(AbsListView view, int firstVisibleItem,
      int visibleItemCount, int totalItemCount) {

  }

  private void setAdapter() {
    if (adapter == null) {
      adapter = new RecentPlayAdapter(this, mList);
      listview.setAdapter(adapter);
    } else {
      adapter.notifyDataSetChanged();
      // pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
      // pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }
  }

  @Override
  public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
    // new GetDataTask().execute();
    pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
  }

  @Override
  public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

  }

  @Override
  public void onBannerClicked(LeBanner banner) {

  }

  @Override
  public void onHeaderClick(StickyListHeadersListView l, View header,
                            int itemPosition, long headerId, boolean currentlySticky) {
    // Toast.makeText(this,
    // "Header " + headerId + " currentlySticky ? " + currentlySticky,
    // Toast.LENGTH_SHORT).show();
  }

  @Override
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public void onStickyHeaderOffsetChanged(StickyListHeadersListView l,
      View header, int offset) {
    if (fadeHeader && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      header.setAlpha(1 - (offset / (float) header.getMeasuredHeight()));
    }
  }

  @Override
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public void onStickyHeaderChanged(StickyListHeadersListView l, View header,
                                    int itemPosition, long headerId) {
    header.setAlpha(1);

    header.setBackgroundColor(0xffffffff);
  }
}
